package com.itheima.intercepto;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class WebInterceptor implements HandlerInterceptor {
    @Override//目标资源方法执行前（true：放行，false：不放行）
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截操作
        HttpServletRequest req = request;
        HttpServletResponse resp = response;
        String token = req.getHeader("token");

        //判断是否含有token头
        if(!StringUtils.hasLength(token)){
            log.info("请求头为空");
            Result error = Result.error("NOT_LOGIN");
            //阿里的fastjosn，用来转换josn格式,返回未登录结果
            String jsonString = JSONObject.toJSONString(error);
            resp.getWriter().write(jsonString);
            return false;
        }
        else{
            try{
                JwtUtils.parseJWT(token);
            }
            catch (Exception e){
                e.printStackTrace();
                log.info("解析令牌失败");
                Result error = Result.error("NOT_LOGIN");
                //阿里的fastjosn，用来转换josn格式,返回未登录结果
                String jsonString = JSONObject.toJSONString(error);
                resp.getWriter().write(jsonString);
                return false;
            }
            log.info("令牌可用");
            return true;
        }
    }

    @Override//目标资源方法执行后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("posthandle");
    }

    @Override//视图渲染完成后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("aftercompletion");
    }
}
